// pages/personal/purchase/recyclingOrder/recyclingOrder.js
import { create, query } from '../../../../utils/service.js'
import { clear } from '../../../../utils/clear.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    date: "",
    files: [],

    // 数据
    companyId: '',
    companyName: '',
    address: '',
    boxNumber: '',//分类箱的数量
    status: '', //分类情况
    statusId: '',
    categoryNumber: '',
    startTime: '',
    addressId: '',
    message: '',
    managerId: '',
    managerName: '',
    managerMobile: '',
    categoryIds: [],
    photoList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    const id = that.options.id
    console.log(id)
    const companyId = app.globalData.companyId
    const name = app.globalData.companyName

    const addressId = app.globalData.addressId
    const addressName = app.globalData.addressName

    const statusId = app.globalData.statusId
    const statusName = app.globalData.statusName

    const boxNumber = app.globalData.boxNumber

    // const PETItems = app.globalData.PETItems
    // const PPItems = app.globalData.PPItems


    const firstList = app.globalData.firstList
    const secondList = app.globalData.secondList
    const thirdList = app.globalData.thirdList
    const fourthList = app.globalData.fourthList  
    


    const managerId = app.globalData.managerId
    const managerName = app.globalData.managerName
    const managerMobile = app.globalData.managerMobile

    let categoryNum = 0
    let categoryIds = []

    firstList.child && firstList.child && firstList.child.map(item => {
      item.child && item.child.map(childItem => {
        if (childItem.checked) {
          categoryNum++
          categoryIds.push(childItem.id)
        }
      })
    })
    secondList.child && secondList.child && secondList.child.map(item => {
      item.child && item.child.map(childItem => {
        if (childItem.checked) {
          categoryNum++
          categoryIds.push(childItem.id)
        }
      })
    })
    thirdList.child && thirdList.child && thirdList.child.map(item => {
      item.child && item.child.map(childItem => {
        if (childItem.checked) {
          categoryNum++
          categoryIds.push(childItem.id)
        }
      })
    })
    fourthList.child && fourthList.child && fourthList.child.map(item => {
      item.child && item.child.map(childItem => {
        if (childItem.checked) {
          categoryNum++
          categoryIds.push(childItem.id)
        }
      })
    })


    // PETItems && PETItems.map(item => {
    //   if (item.checked) {
    //     categoryNum++
    //   }
    // })

    // PPItems && PPItems.map(item => {
    //   if (item.checked) {
    //     categoryNum++
    //   }
    // })

    const categoryNumber = categoryNum == 0 ? '' : "已选" + categoryNum + "个品类"

    if (name.length > 12) {
      var companyName = name.substring(0, 12) + '...'
    } else {
      var companyName = name
    }

    if (addressName.length > 12) {
      var address = addressName.substring(0, 12) + '...'
    } else {
      var address = addressName
    }

    if (statusName.length > 12) {
      var status = statusName.substring(0, 12) + '...'
    } else {
      var status = statusName
    }

    //获取当前时间，格式YYYY-MM-DD
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var startTime = year + seperator1 + month + seperator1 + strDate;

    that.setData({
      companyId: companyId,
      addressId: addressId,
      statusId: statusId,
      companyName: companyName,
      address: address,
      status: status,
      boxNumber: boxNumber,
      categoryNumber: categoryNumber,
      startTime: startTime,
      managerId: managerId,
      managerName: managerName,
      managerMobile: managerMobile,
      categoryIds: categoryIds
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this


    const companyId = app.globalData.companyId
    const name = app.globalData.companyName

    const addressId = app.globalData.addressId
    const addressName = app.globalData.addressName

    const statusId = app.globalData.statusId
    
    const statusName = app.globalData.statusName

    const boxNumber = app.globalData.boxNumber

    // const PETItems = app.globalData.PETItems
    // const PPItems = app.globalData.PPItems

    const managerId = app.globalData.managerId
    const managerName = app.globalData.managerName
    const managerMobile = app.globalData.managerMobile


    const uncategorizedList = app.globalData.uncategorizedList  
    let categoryNum = 0
    let categoryIds = []
    if (statusId == 1){
      uncategorizedList && uncategorizedList.map(item => {
        item.child && item.child.map(childItem => {
          childItem.child && childItem.child.map(x => {
            if(x.checked){
              categoryNum++
              categoryIds.push(x.id)
            }
          })
        })
      })
    }

    if (statusId == 2) {
      uncategorizedList && uncategorizedList.map(item => {
        if (item.checked) {
            categoryNum++
            categoryIds.push(item.id)
          }
      })
    }


    const categoryNumber = categoryNum == 0 ? '' : "已选" + categoryNum + "个品类"

    if (name.length > 12) {
      var companyName = name.substring(0, 12) + '...'
    } else {
      var companyName = name
    }

    if (addressName.length > 12) {
      var address = addressName.substring(0, 12) + '...'
    } else {
      var address = addressName
    }

    if (statusName.length > 12) {
      var status = statusName.substring(0, 12) + '...'
    } else {
      var status = statusName
    }

    //获取当前时间，格式YYYY-MM-DD
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var startTime = year + seperator1 + month + seperator1 + strDate;

    that.setData({
      companyId: companyId,
      addressId: addressId,
      statusId: statusId,
      companyName: companyName,
      address: address,
      status: status,
      boxNumber: boxNumber,
      categoryNumber: categoryNumber,
      startTime: startTime,
      managerId: managerId,
      managerName: managerName,
      managerMobile: managerMobile,
      categoryIds: categoryIds
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const list = that.data.files.concat(res.tempFilePaths)
        let sessionId = wx.getStorageSync('sessionId');
        let header = { 'content-type': 'application/json', 'Cookie': 'PHPSESSID=' + sessionId }
        list.map((item, index) => {
          //上传图片
          const uploadTask =  wx.uploadFile({
            url: 'https://testadmin.lhdrr.com/api/ajax/upload',
            filePath: list[index],
            name: 'file',
            header: header,
            success: function (res) {
              
                wx.hideLoading()
                var data = JSON.parse(res.data)
                const photoList = that.data.photoList
                photoList.push(data.result.url)
                const newPhotos = [...new Set(photoList)]
                console.log("newPhotos")
                console.log(newPhotos)
                that.setData({
                  photoList: newPhotos
                }) 
              
              //do something
            }
          })
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress)
            // console.log('已经上传的数据长度', res.totalBytesSent)
            // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
            if (res.progress != 100) {
              wx.showLoading({
                title: '上传中',
              })
            } else {
              wx.hideLoading()
            }

          })
        })
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  clickImg:function(e){
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    console.log(e)
    var imgArr = this.data.photoList;
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  onChange: function (e) {//货品数量输入框
    var that = this
    const num = e.detail.value
    that.setData({
      boxNumber: num
    })
    app.globalData.boxNumber = num
  },
  onBlur: function (e) {
    const that = this
    const value = e.detail.value
    that.setData({
      message: value
    })
  },
  onAddress: function () {
    const companyId = this.data.companyId
    if (!companyId) {
      wx.showToast({
        title: '请先选择下单公司!',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    wx.navigateTo({
      url: './routes/address/address?id=' + companyId
    })
  },
  onCategory: function () {
    const statusId = this.data.statusId
    if (!statusId) {
      wx.showToast({
        title: '请先选择分类情况!',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    wx.navigateTo({
      url: './routes/category/category?id=' + statusId
    })
  },
  onSubmit: function (e) {//提交数据
    const that = this
    const _this = this.data

    const customer_id = _this.companyId
    const manager_id = _this.managerId
    const factory_id = _this.addressId
    const cargo_count = _this.boxNumber
    const cargo_sort_data = _this.statusId == 1 ? _this.statusId : 0
    const cargo_pick_date = _this.date
    const cargo_images = _this.photoList
    console.log(_this.photoList)
    const seller_remark = _this.message
    const cargo_type = _this.categoryIds

    const data = {
      customer_id,
      manager_id,
      factory_id,
      cargo_count,
      cargo_sort_data,
      cargo_pick_date,
      cargo_images,
      seller_remark,
      cargo_type,
      is_draft: 0
    }

    if (customer_id === '' || manager_id === '' || factory_id === '' || cargo_sort_data === '' || cargo_pick_date === '' || cargo_type === []) {
      wx.showToast({
        title: '请填写完整',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '是否确认提交',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '提交中',
          })
          create({
            url: 'api/waste/purchase/add',
            params: { ...data },
            back: function (data) {
              if (data.code === 200) {
                console.log(data)
                clear()
                that.setData({
                  date: ''
                })
                wx.navigateTo({
                  url: './routes/success/success?=' + that.options.id ,
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  }
})